using System.Data.SqlTypes;
using BuildingBlocks.Core.Entities;
using Identity.Domain.Exceptions;


namespace Identity.Domain.Aggregates
{
    public class UserAggregate : AggregateRoot<Guid>
    {
        public string UserName { get; private set; }
        public string Email { get; private set; }
        public List<string> _roles { get; private set; } = new List<string>();

        public UserAggregate() { }
        public static UserAggregate CreateUser(string userName, string email)
        {
            return new UserAggregate()
            {
                Id=Guid.NewGuid(),
                UserName = userName,
                Email = email,

            };
        }

        public static UserAggregate LoadFromPersistence(Guid userId, string userName, string email, List<string> roles)
        {
            return new UserAggregate()
            {
                Id = userId,
                UserName = userName,
                Email = email,
                _roles = roles

            };
        }

        public void ChangeName(string newName)
        {
            if (string.IsNullOrWhiteSpace(newName)) throw new Exception("用户名不能为空");
            if (UserName == newName) return;
            UserName = newName;
        }
         public void ChangeEmail(string newEmail)
        {
            if (string.IsNullOrWhiteSpace(newEmail)) throw new Exception("邮箱不能为空");
            if (Email == newEmail) return;
            Email = newEmail;
        }

        public void AddRoles(string roleName)
        {
            if (_roles.Contains(roleName)) throw new DomainException("角色已有该权限");

            _roles.Add(roleName);
        }

        public void RemoveRole(string roleName)
        {
            if (!_roles.Contains(roleName)) throw new DomainException("角色没有该权限");

            _roles.Remove(roleName);
        }

        public void ClearRoles()
        {
            _roles.Clear();
        }

    }
}